package com.cheng.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cheng.admin.constant.Constants;
import com.cheng.admin.dao.OrderProductMapper;
import com.cheng.admin.model.Order;
import com.cheng.admin.model.OrderProduct;
import com.cheng.admin.model.Product;
import com.cheng.admin.service.OrderProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 商品-订单 服务实现类
 * </p>
 *
 * @author 起凡
 * @since 2022-01-17
 */
@Service(value = Constants.ORDER_TYPE_PRODUCT)
public class OrderProductServiceImpl extends ServiceImpl<OrderProductMapper, OrderProduct> implements OrderProductService {
    @Autowired
    ProductServiceImpl productService;

    /**
     * 商品订单的价格计算逻辑
     *
     * @param order
     */
    @Override
    public void preprocess(Order order) {
        List<OrderProduct> orderProducts = order.getOrderProducts();
        for (OrderProduct orderProduct : orderProducts) {
            Product product = productService.getById(orderProduct.getProductId());
            orderProduct.setProduct(product);
            // 商品单价*数量
            orderProduct.setPrice(product.getPrice().multiply(BigDecimal.valueOf(orderProduct.getCount())));
            orderProduct.setOrderId(order.getId());
            order.setOriginPrice(order.getOriginPrice().add(orderProduct.getPrice()));
        }
        saveBatch(orderProducts);
        order.setPriceDetail(JSON.toJSONString(orderProducts));
    }

    @Override
    public void rollbackPreprocess(Order order) {
        remove(Wrappers.<OrderProduct>lambdaQuery().eq(OrderProduct::getOrderId, order.getId()));
    }
}
